/*
 * Copyright (c) 2024 iSOFT INFRASTRUCTURE SOFTWARE CO., LTD.
 * easyAda is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */

#pragma once

#include <stdlib/stdint.h>
#include <tools/macros.h>

#define EC_MASK                 (BIT(6) - 1)
#define ESR_EL1_IL_SHIFT        26
#define ESR_EL1_EC_SHIFT        26
#define GET_ESR_EL1_EC(esr_el1) (((esr_el1) >> ESR_EL1_EC_SHIFT) & EC_MASK)

#define ESR_EL1_EC_UNKNOWN      0b000000
#define ESR_EL1_EC_WFI_WFE      0b000001
#define ESR_EL1_EC_ENFP         0b000111
#define ESR_EL1_EC_ILLEGAL_EXEC 0b001110
#define ESR_EL1_EC_SVC_32       0b010001
#define ESR_EL1_EC_SVC_64       0b010101
#define ESR_EL1_EC_MRS_MSR_64   0b011000
#define ESR_EL1_EC_IABT_LEL     0b100000
#define ESR_EL1_EC_IABT_CEL     0b100001
#define ESR_EL1_EC_PC_ALIGN     0b100010
#define ESR_EL1_EC_DABT_LEL     0b100100
#define ESR_EL1_EC_DABT_CEL     0b100101
#define ESR_EL1_EC_SP_ALIGN     0b100110
#define ESR_EL1_EC_FP_32        0b101000
#define ESR_EL1_EC_FP_64        0b101100
#define ESR_EL1_EC_SError       0b101111

static inline void esr_decode_bit(uint64_t esr, uint64_t *EC, uint64_t *IL, uint64_t *ISS)
{
    if (ISS != NULL) {
        *ISS = esr & bitmask(ESR_EL1_EC_SHIFT);
    }
    if (IL != NULL) {
        *IL = esr >> ESR_EL1_IL_SHIFT;
    }
    if (EC != NULL) {
        *EC = esr >> ESR_EL1_EC_SHIFT;
    }
}
